<template>
  <div class="channel-edit">
    <van-cell title="我的频道" :border="false" class="title-text">
      <van-button
        size="mini"
        round
        type="danger"
        plain
        class="edit-btn"
        @click="isEdit = !isEdit"
        >{{ isEdit ? "完成" : "编辑" }}</van-button
      >
    </van-cell>
    <van-grid :gutter="10" class="my-grid">
      <van-grid-item
        class="grid-item"
        v-for="(channel, index) in myChannels"
        :key="index"
        @click="onMyChannelClick(channel, index)"
      >
        <van-icon
          slot="icon"
          name="clear"
          v-show="isEdit && !fiexdChannels.includes(channel.id)"
        ></van-icon>
        <span slot="text" class="text" :class="{ active: index === active }">{{
          channel.name
        }}</span>
      </van-grid-item>
    </van-grid>
    <!-- 频道推荐 -->
    <van-cell title="频道推荐" :border="false"></van-cell>
    <van-grid :gutter="10" class="recommend-grid">
      <van-grid-item
        class="grid-item"
        v-for="(channel, index) in recommendChannels"
        :key="index"
        icon="plus"
        :text="channel.name"
        @click="onAddChannel(channel)"
      />
    </van-grid>
  </div>
</template>

<script>
import {
  getAllChannels,
  addUserChannel,
  deleteUserChannel
} from '@/api/channel.js'
import { mapState } from 'vuex'
import { setItem } from '@/utils/storage'
export default {
  name: 'ChannelEdit',
  components: {},
  props: {
    myChannels: {
      type: Array,
      required: true
    },
    active: {
      type: Number,
      required: true
    }
  },
  data () {
    return {
      allChannels: [],
      isEdit: false,
      fiexdChannels: [0, 11] // 固定频道
    }
  },
  computed: {
    ...mapState(['user']),
    /* 下面的简便方法 */
    recommendChannels () {
      return this.allChannels.filter((channel) => {
        const mychannel = this.myChannels.find((myChannel) => {
          return myChannel.id === channel.id
        })
        return !mychannel
      })
    }
    /*     recommendChannels() {
      const channels = [];
     this.allChannels.forEach((channel) => {
        const ret = this.myChannels.find(myChannel => {
          return myChannel.id === channel.id;
        })
        if (!ret) {
          channels.push(channel);
        }
      })
      console.log(channels);
      return channels;
    }, */
  },
  watch: {},
  created () {
    this.loadAllChannels()
  },
  mounted () {},
  methods: {
    // 获取所有的频道数据
    async loadAllChannels () {
      try {
        const { data } = await getAllChannels()
        this.allChannels = data.data.channels
        console.log(data)
        console.log(this.active)
        // 添加频道
      } catch (err) {
        this.$toast('获取频道列表数据失败')
      }
    },
    async onAddChannel (channel) {
      // 因为recommendChannels是基于this.myChannels计算出来的，所以this.myChannels发生变化，recommendChannels会重新计算
      // this.myChannels是从父组件传递过来的，只有为复杂数据类型的时候才可以进行修改
      // console.log(channel);
      this.myChannels.push(channel)
      //  持久化处理！
      if (this.user) {
        // 分为登录，储存为后端的数据
        try {
          await addUserChannel({
            id: channel.id, // 频道id
            seq: this.myChannels.length // 序号
          })
        } catch (err) {
          this.$toast('保存失败，稍后重试')
        }
      } else {
        // 未登录的情况，储存本地服务器
        setItem('TOUTIAO_CHANNELS', this.myChannels)
      }
    },
    onMyChannelClick (channel, index) {
      /*
        1.判断是否为编辑状态，如果是编辑状态执行删除操作，否则提供跳转
        2.使用splice删除myCannels
        3.如果要删除的索引小于等于激活的索引，需要把激活的索引减一
        4.如果要删除的频道是固定频道中的需要return阻止
        */
      // console.log(channel,index);
      if (this.isEdit) {
        // 固定频道不删除！
        // 1.固定不删除的频道项
        if (this.fiexdChannels.includes(channel.id)) {
          return
        }
        // 2.删除频道项
        this.myChannels.splice(index, 1)
        /*
          3.如果删除的激活频道之前的频道，则更新激活的频道项
          1.参数1:要删除的元素；参数2：删除几个元素
          */
        if (index <= this.active) {
          this.$emit('update-active', this.active - 1, true)
        }
        // 4.处理持久化
        this.deleteChannel(channel)
      } else {
        /* 非编辑状态 */
        this.$emit('update-active', index, false)
      }
    },
    async deleteChannel (channel) {
      try {
        if (this.user) {
          deleteUserChannel(channel.id)
        } else {
          // 未登录的情况，储存本地服务器
          setItem('TOUTIAO_CHANNELS', this.myChannels)
        }
      } catch (err) {
        this.$toast('操作失败，请稍后重试~')
      }
    }
  }
}
</script>

<style scoped lang="less">
.channel-edit {
  padding: 85px 0;
  .title-text {
    font-size: 32px;
    color: #333333;
  }
  .edit-btn {
    width: 104px;
    height: 48px;
    font-size: 26px;
    color: #f85959;
    border: 1px solid #f85959;
    transform: translateY(-10px);
  }

  /deep/ .grid-item {
    width: 160px;
    height: 86px;
    .van-grid-item__content {
      white-space: nowrap;
      background: #f4f5f6;
      .van-grid-item__text {
        font-size: 28px;
        color: #222;
        margin-top: 0;
      }
    }
    .text {
      font-size: 28px;
    }
    .active {
      color: aqua;
    }
    .van-grid-item__icon-wrapper {
      position: unset;
    }
  }

  /deep/ .my-grid {
    .grid-item {
      .van-icon-clear {
        position: absolute;
        right: -10px;
        top: -10px;
        font-size: 15px;
        color: #cacaca;
        z-index: 2;
      }
    }
  }

  /deep/ .recommend-grid {
    .grid-item {
      .van-grid-item__content {
        flex-direction: row;
        .van-icon-plus {
          font-size: 28px;
          margin-right: 6px;
        }
        .van-grid-item__text {
          margin-top: 0;
        }
      }
    }
  }
}
</style>
